﻿namespace WebPacker.Tool.Sources
{
	using System;
	using System.IO;
	using System.Linq;
	using WebPacker.Configuration;
	using WebPacker.Tool.Sources;

	internal class PacksSource : ISource
	{
		private readonly Configuration configuration;
		private readonly string fileName;
		private PackInfo[] packs;

		public PacksSource(Configuration configuration, string fileName)
		{
			if (configuration == null)
			{
				throw new ArgumentNullException("configuration");
			}

			if (fileName == null)
			{
				throw new ArgumentNullException("fileName");
			}

			this.configuration = configuration;
			this.fileName = fileName;
		}

		public PackInfo[] Packs
		{
			get { return packs; }
		}

		public Configuration Configuration
		{
			get { return configuration; }
		}

		public void Open()
		{
			if (!File.Exists(fileName))
			{
				throw ToolException.FileNotFound(fileName);
			}

			var packInfos = WebPackerConfiguration.DeserializePackInfoCollection(fileName);

			if (packInfos.VersionGeneratorName != null)
			{
				configuration.VersionGeneratorName = packInfos.VersionGeneratorName;
			}

			packs = packInfos.ToArray();
		}
	}
}
